跳到主要内容

gorm sql


build := helper.SqlBuilder{
Where: "cover LIKE 'https://%' and where id = ? and status = ?",
WhereParam: []interface{}{bookID, 5},
}
total, err := b.teachInfoV2Model.GetCount(ctx, &build)



func (d *TeachingVersionInfoModel) GetCount(ctx *gin.Context, build *helper.SqlBuilder) (int64, error) {
var data int64
tableName := new(knowledgeV2Schema.TeachingVersionInfoV2).TableName()
err := build.Build(d.Slave.Orm.WithContext(ctx).Table(tableName)).Count(&data).Error
return data, err
}

package helper

import (
"fmt"

"gorm.io/gorm"
)

const (
DefaultPage = 1
DefaultLimit = 10
)

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if page == 0 {
page = 1
}
switch {
case pageSize > 100:
pageSize = 100
case pageSize <= 0:
pageSize = 10
}
offset := (page - 1) * pageSize
return db.Offset(offset).Limit(pageSize)
}
}

// SqlBuilder sql生成器 简单版
type SqlBuilder struct {
Field string // 查询字段 如:*
Where string // where语句 如:id=? and xxx in (?)
WhereParam []interface{} // where 绑定参数
Order string // 排序 如:id asc
Group string // group by
Limit int // 分页设置 10
Page int // 第几页 1
IsPage bool // 是否分页
}

// GetPage 获取第几页
func (s *SqlBuilder) GetPage() int {

if s.Page <= 0 {
s.Page = DefaultPage
}

return s.Page
}

// GetLimit 获取分页设置
func (s *SqlBuilder) GetLimit() int {
if s.Limit <= 0 {
s.Limit = DefaultLimit
}
return s.Limit
}

// GetOffset 获取offset
func (s *SqlBuilder) GetOffset() int {
limit := s.GetLimit()
page := s.GetPage()
return (page - 1) * limit
}

// Build 生成
func (s *SqlBuilder) Build(db *gorm.DB) *gorm.DB {
// 设置字段
if s.Field != "" {
db = db.Select(s.Field)
}

// sql类型的查询
if s.Where != "" {
db = db.Where(s.Where, s.WhereParam...)
}

if s.Order != "" {
db = db.Order(s.Order)
}

if s.Group != "" {
db = db.Group(s.Group)
}

// 设置分页
if s.IsPage {
db = db.Limit(s.GetLimit()).Offset(s.GetOffset())
}

return db
}

// AddWhere 添加 and where条件
func (s *SqlBuilder) AddWhere(where string, params ...interface{}) {
if s.Where == "" {
s.Where = where
} else {
s.Where = fmt.Sprintf(" %s AND %s ", s.Where, where)
}

if len(params) > 0 {
for _, v := range params {
s.WhereParam = append(s.WhereParam, v)
}
}
}

// OrWhere 添加 or where条件
func (s *SqlBuilder) OrWhere(where string, params ...interface{}) {
if s.Where == "" {
s.Where = where
} else {
s.Where = fmt.Sprintf(" %s OR %s ", s.Where, where)
}

if len(params) > 0 {
for _, v := range params {
s.WhereParam = append(s.WhereParam, v)
}
}
}